#pragma once
#include<pthread.h>
#include<iostream>
namespace LockModule
{
    class Mutex
    {
        public:
        Mutex()
        {
            //构造函数中把初始化
            int n=pthread_mutex_init(&_lock,nullptr);
            if(n!=0)
            {
                std::cerr<<"初始化错误"<<std::endl;
            }
            (void)n;//目前还不用到n,所以先转为void,避免编译器警告
        }
        void Lock()
        {
            int n = ::pthread_mutex_lock(&_lock);
            (void)n;
        }
        void Unlock()
        {
            int n = ::pthread_mutex_unlock(&_lock);
            (void)n;
        }
        pthread_mutex_t* LockPtr()
        {
            return &_lock;
        }
        ~Mutex()
        {
            int n=pthread_mutex_destroy(&_lock);
            if(n!=0)
            {
                std::cerr<<"解锁失败"<<std::endl;
            }
        }
        private:
        pthread_mutex_t _lock;
    };

    //这个类的作用：这个类创建临时对象后，出了作用域就会自己析构，达到解锁的作用，就不用自己上锁解锁
    class LockGuard
    {
    public:
        LockGuard(Mutex &mtx):_mtx(mtx)
        {
            _mtx.Lock();
        }
        ~LockGuard()
        {
            _mtx.Unlock();
        }
    private:
        Mutex &_mtx;
    };
}